package com.doge.service.admin.goods;

import com.alibaba.druid.util.StringUtils;
import com.doge.bean.base.BaseData;
import com.doge.bean.base.BaseParam;
import com.doge.bean.bo.goods.*;

import com.doge.bean.pojo.category.Category;
import com.doge.bean.pojo.goods.*;
import com.doge.bean.vo.goods.*;
import com.doge.exception.Delete502Exception;
import com.doge.mapper.*;
import com.doge.service.admin.goods.GoodsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * @program: project2-wechat-mall
 * @description:
 * @author: 305905917@qq.com
 * @create: 2021-11-29 21:57
 **/

@Service
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    GoodsSpecificationMapper goodsSpecificationMapper;
    @Autowired
    GoodsProductMapper goodsProductMapper;
    @Autowired
    GoodsAttributeMapper goodsAttributeMapper;

    @Autowired
    CategoryMapper categoryMapper;

    @Override
    public BaseData list(BaseParam baseParam, String goodsSn, String name, Integer goodsId) {
        //分页
        if (baseParam.getLimit() != 0) {
            PageHelper.startPage(baseParam.getPage(), baseParam.getLimit());
        }
        //设置条件查询
        GoodsExample example = new GoodsExample();
        GoodsExample.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(goodsSn)) {
            //注意此处的Like方法需要自己手懂修改
            goodsSn = "%" + goodsSn + "%";
            criteria.andGoodsSnLike(goodsSn);
        }
        if (!StringUtils.isEmpty(name)) {
            name = "%" + name + "%";
            criteria.andNameLike(name);
        }
        if (goodsId != null) {
            criteria.andIdEqualTo(goodsId);
        }
        if (baseParam.getSort() != null || baseParam.getOrder() != null) {
            example.setOrderByClause(baseParam.getSort() + " " + baseParam.getOrder());
        }
        criteria.andDeletedEqualTo(false);
        List<Goods> goodsList = goodsMapper.selectByExample(example);
        PageInfo info = new PageInfo(goodsList);
        //利用分页插件获取total
        long total = info.getTotal();
        return BaseData.list(goodsList, total);
    }

    @Override
    public CatAndBrandVO catAndBrand() {
        CatAndBrandVO catAndBrandVO = new CatAndBrandVO();
        List<CategoryByCatAndBrandVO> categoryList = new ArrayList<>();
        categoryList = goodsMapper.selectCategoryList();
        List<BrandListByCatAndBrandVO> brandList = goodsMapper.selectBrandIdAndName();
        catAndBrandVO.setCategoryList(categoryList);
        catAndBrandVO.setBrandList(brandList);
        return catAndBrandVO;
    }

    /**
     * 上架商品
     *
     * @param createGoodsBO
     */
    @Override
    public void crateGoods(CreateGoodsBO createGoodsBO) {
        //获取Goods的请求参数
        CreateOfGoodsBO goodsBO = createGoodsBO.getGoods();
        //获取specifications
        List<CreateOfSpecificationsBO> specifications = createGoodsBO.getSpecifications();
        //获取products
        LinkedList<CreateOfProducts> products = createGoodsBO.getProducts();
        //数据插入goods表
        BigDecimal price = products.getFirst().getPrice();
//        BigDecimal bigDecimal = new BigDecimal(price);
        Goods goods = new Goods();
        BeanUtils.copyProperties(goodsBO, goods);
        Short random = (short) (Math.random() * 100);
        goods.setSortOrder(random);
        goods.setAddTime(new Date());
        goods.setRetailPrice(price);
        goodsMapper.insertSelective(goods);
        //数据插入goodsSpecifications
        for (CreateOfSpecificationsBO specification : specifications) {
            GoodsSpecification goodsSpecification = new GoodsSpecification();
            BeanUtils.copyProperties(specification, goodsSpecification);
            goodsSpecification.setGoodsId(goods.getId());
            goodsSpecification.setAddTime(new Date());
            goodsSpecificationMapper.insertSelective(goodsSpecification);
        }
        //数据插入goodsProducts
        for (CreateOfProducts product : products) {
            GoodsProduct goodsProduct = new GoodsProduct();
            //TODO BeanUtils
            BeanUtils.copyProperties(product, goodsProduct);
            goodsProduct.setGoodsId(goods.getId());
            goodsProduct.setAddTime(new Date());
            goodsProduct.setId(null);
            goodsProductMapper.insertSelective(goodsProduct);
        }
        //数据插入goodsAttributes
        List<CreateOfAttributes> attributes = createGoodsBO.getAttributes();
        for (CreateOfAttributes attribute : attributes) {
            GoodsAttribute goodsAttribute = new GoodsAttribute();
            BeanUtils.copyProperties(attribute, goodsAttribute);
            goodsAttribute.setGoodsId(goods.getId());
            goodsAttribute.setAddTime(new Date());
            goodsAttributeMapper.insertSelective(goodsAttribute);
        }


    }

    @Override
    public void deleteGoods(Goods goods) throws Delete502Exception {
        // 根据 id和 name删除商品（缺一不可！）
        GoodsExample example = new GoodsExample();
        example.createCriteria().andNameEqualTo(goods.getName()).andIdEqualTo(goods.getId()).andDeletedEqualTo(false);
        // 逻辑删除，不是真实的删除
        goods.setDeleted(true);
        int i = goodsMapper.updateByExampleSelective(goods, example);
        if (i != 1)
            throw new Delete502Exception("商品删除失败！");
    }

    @Override
    public GoodsDetailVO selectDetailByGoodsId(Integer goodsId) {
        GoodsDetailVO goodsDetailVO = new GoodsDetailVO();
        //goods
        Goods goods = goodsMapper.selectByPrimaryKey(goodsId);
        Integer categoryId = goods.getCategoryId();
        //cateGoryIds
        Category category = categoryMapper.selectByPrimaryKey(categoryId);
        Integer pid = category.getPid();
        List<CateGoryIds> cateGoryIdsList = new ArrayList<>();
        CateGoryIds cateGoryIds = new CateGoryIds();
        cateGoryIds.setId(categoryId);
        cateGoryIds.setPid(pid);
        cateGoryIdsList.add(cateGoryIds);
        //attributes
        GoodsAttributeExample goodsAttributeExample = new GoodsAttributeExample();
        goodsAttributeExample.createCriteria().andGoodsIdEqualTo(goodsId);
        List<GoodsAttribute> goodsAttributes = goodsAttributeMapper.selectByExample(goodsAttributeExample);
        //specifications
        GoodsSpecificationExample goodsSpecificationExample = new GoodsSpecificationExample();
        goodsSpecificationExample.createCriteria().andGoodsIdEqualTo(goodsId);
        List<GoodsSpecification> goodsSpecifications = goodsSpecificationMapper.selectByExample(goodsSpecificationExample);
        //products
        GoodsProductExample goodsProductExample = new GoodsProductExample();
        goodsProductExample.createCriteria().andGoodsIdEqualTo(goodsId);
        List<GoodsProduct> goodsProducts = goodsProductMapper.selectByExample(goodsProductExample);
        //赋值给返回类
        goodsDetailVO.setGoods(goods);
        goodsDetailVO.setCateGoryIds(cateGoryIdsList);
        goodsDetailVO.setAttributes(goodsAttributes);
        goodsDetailVO.setSpecifications(goodsSpecifications);
        goodsDetailVO.setProducts(goodsProducts);
        return goodsDetailVO;

    }

    @Override
    public void update(UpdateGoodsBO updateGoodsBO) {
        //修改goods
        Goods goods = updateGoodsBO.getGoods();
        goods.setUpdateTime(new Date());
        goodsMapper.updateByPrimaryKeySelective(goods);
        Integer goodsId = goods.getId();
        //修改specifications
        List<GoodsSpecification> specifications = updateGoodsBO.getSpecifications();
        //GoodsSpecificationExample goodsSpecificationExample = new GoodsSpecificationExample();
        //goodsSpecificationExample.createCriteria().andGoodsIdEqualTo(goodsId);
        for (GoodsSpecification specification : specifications) {
            specification.setUpdateTime(new Date());
            //goodsSpecificationMapper.updateByExampleSelective(specification, goodsSpecificationExample);
            goodsSpecificationMapper.updateByPrimaryKeySelective(specification);
        }
        //修改attributes
        List<GoodsAttribute> attributes = updateGoodsBO.getAttributes();
        GoodsAttributeExample goodsAttributeExample = new GoodsAttributeExample();
        GoodsAttributeExample.Criteria criteria = goodsAttributeExample.createCriteria();
        for (GoodsAttribute attribute : attributes) {
            if (attribute.getId() == null) {
                attribute.setAddTime(new Date());
                attribute.setGoodsId(goodsId);
                goodsAttributeMapper.insertSelective(attribute);
            } else {
                criteria.andGoodsIdEqualTo(goodsId);
                criteria.andIdEqualTo(attribute.getId());
                attribute.setUpdateTime(new Date());
                goodsAttributeMapper.updateByExampleSelective(attribute, goodsAttributeExample);
            }
        }
        //修改products
        List<GoodsProduct> products = updateGoodsBO.getProducts();
//        GoodsProductExample goodsProductExample = new GoodsProductExample();
//        goodsProductExample.createCriteria().andGoodsIdEqualTo(goodsId);

        for (GoodsProduct product : products) {
            product.setUpdateTime(new Date());
            goodsProductMapper.updateByPrimaryKeySelective(product);
            int count =0;
            if (count==0){
              int i =  goodsMapper.updateRetailPrice(product.getPrice(),goodsId);
                count++;
            }
        }

    }

}
